package blacknWhite.Libraries;

import java.util.ArrayList;
import java.util.Locale;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.sqlite.SQLiteDatabase;
import android.preference.PreferenceManager;
import android.view.View;
import android.widget.ArrayAdapter;
import blacknWhite.MarketSalesMonitor.PreferencesActivity;
import blacknWhite.MarketSalesMonitor.R;

import com.gc.android.market.api.MarketSession;
import com.gc.android.market.api.MarketSession.Callback;
import com.gc.android.market.api.model.Market.Comment;
import com.gc.android.market.api.model.Market.CommentsRequest;
import com.gc.android.market.api.model.Market.CommentsRequest.Builder;
import com.gc.android.market.api.model.Market.CommentsResponse;
import com.gc.android.market.api.model.Market.RequestContext;
import com.gc.android.market.api.model.Market.ResponseContext;

public class MarketLibrary {
	static Lock lock = new ReentrantLock();

	public static void refreshComments(View progressBar,
			final ArrayAdapter<View> dataAdapter, Context ctx) {
		try {
			SharedPreferences sp = PreferenceManager
					.getDefaultSharedPreferences(ctx);

			String email = sp.getString("email", "");
			if (email.contentEquals("")) {
				if (progressBar != null) {
					Utils.showToast(ctx, ctx.getString(R.string.errorEmail));
					ctx.startActivity(new Intent(ctx, PreferencesActivity.class));
				}
				return;
			}

			String password = sp.getString("password", "");
			if (password.contentEquals("")) {
				if (progressBar != null) {
					Utils.showToast(ctx, ctx.getString(R.string.errorPassword));
					ctx.startActivity(new Intent(ctx, PreferencesActivity.class));
				}
				return;
			}

			ArrayList<String> packageIds = new ArrayList<String>();
			String packageId = sp.getString("namespaceApp01", "");
			if (!packageId.contentEquals(""))
				packageIds.add(packageId);
			packageId = sp.getString("namespaceApp01", "");
			if (!packageId.contentEquals(""))
				packageIds.add(packageId);
			packageId = sp.getString("namespaceApp02", "");
			if (!packageId.contentEquals(""))
				packageIds.add(packageId);
			packageId = sp.getString("namespaceApp03", "");
			if (!packageId.contentEquals(""))
				packageIds.add(packageId);
			packageId = sp.getString("namespaceApp04", "");
			if (!packageId.contentEquals(""))
				packageIds.add(packageId);
			packageId = sp.getString("namespaceApp05", "");
			if (!packageId.contentEquals(""))
				packageIds.add(packageId);
			packageId = sp.getString("namespaceApp06", "");
			if (!packageId.contentEquals(""))
				packageIds.add(packageId);
			packageId = sp.getString("namespaceApp07", "");
			if (!packageId.contentEquals(""))
				packageIds.add(packageId);
			packageId = sp.getString("namespaceApp08", "");
			if (!packageId.contentEquals(""))
				packageIds.add(packageId);
			packageId = sp.getString("namespaceApp09", "");
			if (!packageId.contentEquals(""))
				packageIds.add(packageId);
			packageId = sp.getString("namespaceApp10", "");
			if (!packageId.contentEquals(""))
				packageIds.add(packageId);
			if (packageIds.isEmpty()) {
				if (progressBar != null) {
					Utils.showToast(ctx, ctx.getString(R.string.errorPackages));
					ctx.startActivity(new Intent(ctx, PreferencesActivity.class));
				}
				return;
			}

			if (progressBar != null)
				progressBar.setVisibility(View.VISIBLE);
			GetComments(progressBar, ctx, dataAdapter, email, password,
					packageIds);
		} catch (Exception e) {
			final Runnable refreshDataFromAsync = new Runnable() {
				public void run() {
					dataAdapter.notifyDataSetChanged();
				}
			};
			if (dataAdapter != null)
				Utils.handler.post(refreshDataFromAsync);

			Utils.LogException(e);
		}
	}

	private static void GetComments(final View progressBar,
			final Context context, final ArrayAdapter<View> dataAdapter,
			final String email, final String password,
			final ArrayList<String> packageIds) {

		new Thread(new Runnable() {
			public void run() {
				if (!lock.tryLock())
					return;
				getCommentsThread(progressBar, context, dataAdapter, email,
						password, packageIds);
			}
		}).start();
	}

	private static boolean getCommentsThread(final View progressBar,
			final Context context, final ArrayAdapter<View> dataAdapter,
			final String email, final String password,
			final ArrayList<String> packageIds) {
		try {

			final MarketSession session = new MarketSession();
			session.setLocale(new Locale(""));

			RequestContext.Builder contextBuilder = session.getContext();

			// contextBuilder.setDeviceAndSdkVersion(android.os.Build.DEVICE +
			// ":"
			// + VERSION.SDK_INT);
			// String androidId = Secure.getString(context.getContentResolver(),
			// Secure.ANDROID_ID);
			// contextBuilder.setAndroidId(androidId);

			contextBuilder.setAndroidId("3000000000000000");
			session.login(email, password);

			for (final String packageId : packageIds) {

				// // Need to get app id
				// String query = "pname:" + packageId;
				// AppsRequest appsRequest = AppsRequest.newBuilder()
				// .setQuery(query).setStartIndex(0).setEntriesCount(1)
				// .setWithExtendedInfo(false).build();
				//
				// session.append(appsRequest, new Callback<AppsResponse>() {
				// public void onResult(ResponseContext ctx,
				// AppsResponse response) {
				// // Your code here
				// // response.getApp(0).getCreator() ...
				// // see AppsResponse class definition for more infos
				// if (response == null)
				// return;
				// for (App app : response.getAppList()) {
				// // App app = response.getApp(0);
				// String appId = app.getId();

				Builder req = CommentsRequest.newBuilder();
				req.setAppId(packageId);
				req.setStartIndex(0);
				req.setEntriesCount(10);
				// req.getEntriesCount();
				CommentsRequest commentsRequest = req.build();

				Callback<CommentsResponse> responseHandler = new Callback<CommentsResponse>() {
					public void onResult(ResponseContext resContext,
							CommentsResponse response) {
						parseComments(context, response, packageId);
					}
				};

				session.append(commentsRequest, responseHandler);
				session.flush();
				// }
				// }
				// });
				// session.flush();
			}
		} catch (Throwable ex) {
			Utils.LogException(ex);
			return false;
		} finally {
			try {
				// if (mOpenHelper != null)
				// mOpenHelper.close();

				lock.unlock();
				final Runnable refreshDataFromAsync = new Runnable() {

					public void run() {
						try {
							if (progressBar != null)
								progressBar.setVisibility(View.GONE);
							if (dataAdapter != null)
								dataAdapter.notifyDataSetChanged();
						} catch (Exception ex) {
							Utils.LogException(ex);
						}
					}
				};
				Utils.handler.post(refreshDataFromAsync);
			} catch (Throwable ex) {
				Utils.LogException(ex);
			}
		}
		return true;
	}

	private static void parseComments(Context context,
			CommentsResponse response, String packageId) {
		System.out.println("Response : " + response);

		if (response == null)
			return;

		AppDatabase mOpenHelper = null;
		mOpenHelper = new AppDatabase(context);
		final SQLiteDatabase db = mOpenHelper.getWritableDatabase();

		try {
			for (Comment comment : response.getCommentsList()) {
				String authorName = "";
				if (comment.hasAuthorName())
					authorName = comment.getAuthorName();
				long creationTime = 0;
				if (comment.hasCreationTime())
					creationTime = comment.getCreationTime();
				int rating = 0;
				if (comment.hasRating())
					rating = comment.getRating();
				String text = "";
				if (comment.hasText())
					text = comment.getText();
				AddComment(db, packageId, authorName, creationTime, rating,
						text);
			}
		} catch (Throwable ex) {
			Utils.LogException(ex);
		} finally {
			db.close();
		}
	}

	public static void AddComment(SQLiteDatabase db, String packageId,
			String authorName, long creationTime, int rating, String text) {
		ContentValues cv = new ContentValues();
		cv.put(AppDatabase.AppCommentsColumns.PACKAGE_ID, packageId);
		cv.put(AppDatabase.AppCommentsColumns.AUTHOR_NAME, authorName);
		cv.put(AppDatabase.AppCommentsColumns.CREATION_TIME, creationTime);
		cv.put(AppDatabase.AppCommentsColumns.RATING, rating);
		cv.put(AppDatabase.AppCommentsColumns.TEXT, text);
		try {
			db.insertOrThrow(AppDatabase.Tables.APP_COMMENTS, null, cv);
		} catch (Throwable ex) {
			Utils.LogException(ex);
		}
	}

}
